﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using Shared;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Configuration;
using System.Threading;
using RastinArgham.Robots.Registrator.RobotWCF;
using Mani.Common;

namespace RastinArgham.Robots.Registrator
{
    class Program
    {
        private static List<Register> registrationData = new List<Register>();

        static void Main(string[] args)
        {
            Host();

            while (true)
            {
                Console.WriteLine("Robot is awake and is going to start his job!");
                KillJobs();
                GetRegistrationData();

                Console.WriteLine("Robot has " + registrationData.Count + " task(s) to perform!");
                foreach (var item in registrationData)
                {
                    Console.WriteLine("Executing OrderID " + item.OrderId);
                    Execute(item);

                    while ( Process.GetProcessesByName("Registration").Length != 0 ) {
                        Thread.Sleep(30 * 1000);
                    }
                }

                Console.WriteLine("Robot is going to sleep for 2 minutes!");
                Thread.Sleep( 2 * 60 * 1000 );
            }
        }

        private static void GetRegistrationData()
        {
            registrationData.Clear();

            CRMRobotWCFClient robotService = new CRMRobotWCFClient();
            RastinArgham.Robots.Registrator.RobotWCF.MobinContact[] contacts = robotService.GetRegistrationContacts();

            foreach (var item in contacts)
            {
                if (String.IsNullOrEmpty(item.Username))
                    robotService.ContactRegistrationReport(item.OrderId, "", false, "کاربر فاقد شناسه کاربری می باشد");
                else
                    registrationData.Add( 
                        new Register { 
                            Identity = item.Username, 
                            OrderId = item.OrderId,
                            ActualHighSpeed = true,
                            ActualMadarek = 0,
                            ActualId = item.IdentityNumber,
                            ActualIssue = item.IdentityIssuePlace,
                            ActualMajor = item.EducationalMajor,
                            Address = item.Address,
                            ActualEmploy = item.Job,
                            AddressModem = item.InstallationAddress,
                            BirthDate = item.Birthday.ToJalali(),
                            BuilidingName = item.InstallationBuildingName,
                            City = item.CityId,
                            CompanyBaseActivity = item.CompanyActivityField,
                            CompanyFullName = item.CompanyEnglishName,
                            CompanyManagerGrade = item.ManagerAcademicDegree,
                            CompanyName = item.CompanyName,
                            Economics = "",
                            Email = item.Email,
                            FatherName = item.FatherName,
                            Fax = item.Fax,
                            ManagerBirthDate = item.ManagerBirthday.ToJalali(),
                            ManagerFullname = item.ManagerEnglishFullName,
                            ManagerGrade = item.ManagerAcademicDegree,
                            ManagerLastName = item.ManagerLastName,
                            ManagerMajor = item.ManagerEducationalMajor,
                            ManagerMelliCode = item.ManagerNationalCode,
                            ManagerName = item.ManagerFirstName,
                            MelliCode = item.NationalCode,
                            Mobile = item.Mobile,
                            PersonalFullName = item.PersonalEnglishFullName,
                            PersonalLastName = item.PersonalLastName,
                            PersonalName = item.PersonalFirstName,
                            PlaceCity = item.InstallationCityId,
                            PlaceFloor = item.InstallationFloor,
                            PlaceOstan = item.InstallationProvinceId,
                            PlaceTelNum = item.Tel,
                            PlaceVahedNum = item.InstallationVahed,
                            Plaque = item.InstallationPlaque,
                            PostalCode = item.ZipCode,
                            ProductTitle = item.ProductTitle,
                            Region = 1,
                            RegNo = item.RegistrationNumber,
                            RequestType = item.RequestType,
                            ServiceDuration = item.ServiceDuration,
                            Tel = item.Tel,
                            Webiste = item.WebSite,
                        });
            }
        }

        private static void Execute(Register data)
        {
            try
            {
                data.TimeStamp = DateTime.Now;

                string parameter = String.Empty;

                DataContractSerializer ds = new DataContractSerializer(typeof(Register));

                using (MemoryStream m = new MemoryStream())
                {
                    ds.WriteObject(m, data);

                    byte[] buffer = m.ToArray();

                    parameter =
                        Convert.ToBase64String(buffer) + " " +
                        (bool.Parse(ConfigurationSettings.AppSettings["debug"].ToString()) ? "debug" : "nodebug") + " " +
                        ConfigurationSettings.AppSettings["timeout"].ToString() + " " +
                        ConfigurationSettings.AppSettings["url"].ToString() + " " +
                        ConfigurationSettings.AppSettings["interval"].ToString() + " " +
                        ConfigurationSettings.AppSettings["username"].ToString() + " " +
                        ConfigurationSettings.AppSettings["password"].ToString() + " " +
                        ConfigurationSettings.AppSettings["special-username"].ToString() + " " +
                        ConfigurationSettings.AppSettings["special-password"].ToString();

                    string s = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Registration.exe";

                    Process.Start(s, parameter);

                }
            }
            catch (Exception ex)
            {
#if debug
                MessageBox.Show(ex.Message);
#endif
                Console.WriteLine(ex.Message);
                //SetState(false);
            }

        }

        private static void KillJobs()
        {
            foreach (var item in Process.GetProcessesByName("Registration"))
            {
                item.Kill();
            }
        }

        private static void Host()
        {
            ServiceHost syncHost =
                new ServiceHost(
                    typeof(ReportService),
                    new Uri[] { new Uri("net.pipe://localhost/Registration") });

            syncHost.AddServiceEndpoint(
                typeof(IReportService),
                new NetNamedPipeBinding(),
                "ReportService");

            syncHost.Open();
        } 
    }
}
